<script setup>
import { ref, reactive, onMounted, inject, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { globalStore } from '@/stores/global.js'

import {
  UploadFilled,
  Search,
  WarningFilled,
  ArrowUpBold,
  ArrowDownBold,
  Back,
  Right,
  CircleCheckFilled,
  Tools,
  Loading,
  Download,
  QuestionFilled,
} from '@element-plus/icons-vue'

import AddIcon from '@/components/icons/AddIcon.vue'
import SaveIcon from '@/components/icons/SaveIcon.vue'
import LookIcon from '@/components/icons/LookIcon.vue'
import ReplaceIcon from '@/components/icons/ReplaceIcon.vue'
import ScriptFileIcon from '@/components/icons/ScriptFileIcon.vue'
import UploadIcon from '@/components/icons/UploadIcon.vue'
import DownloadIcon from '@/components/icons/DownloadIcon.vue'

const storeGlobal = globalStore()
const $http = inject('$http')

const state = reactive({
  allPackageName: [],
  scriptPack: [],
  scriptPackCache: [],
  scriptPackActive: 0,
  searchScriptPack: '',
  scriptPackData: {},

  tableData: [],
  // 上传脚本
  oddDialogVisible: false,
  oddDialogTitle: '上传脚本 -',
  oddDialogData: {
    packageId: 0,
    scriptCode: '',
    scriptName: '',
    scriptFile: '',
  },
  // 查看脚本
  lookDialogVisible: false,
  lookDialogTitle: '查看脚本 -',
  lookDialogData: {},
  // 批量上传
  moreDialogVisible: false,
  moreDialogData: {
    packageId: 0,
    scriptFiles: []
  }
})

watch(() => state.searchScriptPack, (newVal, oldVal) => {
  if (!newVal) {
    state.scriptPack = state.scriptPackCache
  }
  let scriptPack = []
  state.scriptPackCache.forEach(i => {
    if (i.packageName.indexOf(newVal) >= 0) {
      scriptPack.push(i)
    }
  })
  state.scriptPack = scriptPack
})

const allPackageNameLength = computed(() => state.allPackageName.length);

onMounted(() => {
  state.allPackageName = storeGlobal.scriptTypeList
  getScriptPack()
})
const getScriptPack = () => {
  $http('/api/script-package/list').then((res) => {
    state.scriptPack = res
    state.scriptPackCache = res
    if (res.length != 0) {
      state.scriptPackActive = res[0].packageId
      state.scriptPackData = res[0]
      $http('/api/script/list', { params: { packageId: res[0].packageId } }).then((res) => {
        let table = res.map((i) => {
          if (!i.scriptName) {
            let data = storeGlobal.scriptTypeList.find(
              (j) => j.id.toUpperCase() == i.scriptCode.toUpperCase()
            )
            i['scriptName'] = data?.name
          }
          return i
        })
        state.tableData = table
      })
    }
  })
}
function addScriptPack() {
  $http
    .post('/api/script-package/add', { packageName: '自定义脚本包', description: '' })
    .then((res) => {
      if (res.errorMessage) {
        ElMessage.error(res.errorMessage)
      } else {
        ElMessage.success('已创建空白脚本包，请上传所需脚本')
        setTimeout(() => {
          getScriptPack()
        }, 300)
      }
    })
}

function scriptPackSubmit(){
  console.log(state.scriptPackData, "数据")
  $http
    .post('/api/script-package/update', { packageId: state.scriptPackData.packageId, packageName: state.scriptPackData.packageName, description: state.scriptPackData.description })
    .then((res) => {
      if(res == 'success') {
        ElMessage.success('脚本包信息已保存')
      }
    })
}
function onScriptPack(item) {
  state.scriptPackActive = item.packageId
  state.scriptPackData = item
  $http('/api/script/list', { params: { packageId: item.packageId } }).then((res) => {
    state.tableData = res
  })
}
function openLookDialog(row) {
  state.lookDialogTitle = '查看脚本 - ' + row.scriptCode
  $http('/api/script/item-content', {
      params: {itemId: row.itemId}
    })
    .then((res) => {
      state.lookDialogData = res
      state.lookDialogVisible = true
    })

}
function openOddDialog(row) {
  state.oddDialogTitle = '上传脚本 - ' + row.scriptName
  state.oddDialogData = {
    packageId: state.scriptPackData.packageId,
    scriptCode: row.scriptCode,
    scriptName: row.scriptName,
  }
  state.oddDialogVisible = true
}


function moreUploadChange(uploadFile){
  state.moreDialogData.scriptFiles = [uploadFile, ...state.moreDialogData.scriptFiles]
}
function removeMoreFile(uploadFile) {
  state.moreDialogData.scriptFiles = state.moreDialogData.scriptFiles.filter(i => i.name != uploadFile.name)
}
function moreUpload() {
  let fileArr = state.moreDialogData.scriptFiles.map(i => i.raw)
  const formData = new FormData()
  formData.append('packageId', state.scriptPackData.packageId)
  fileArr.forEach((i, index) => {
    formData.append(`scriptFiles`, i)
  })
  $http
    .post('/api/script/batch-upload', formData, {
      transformRequest: [], // 禁止数据转换
      headers: { 'Content-Type': 'multipart/form-data' },
    })
    .then((res) => {
      ElMessage.success('上传成功')
      state.moreDialogVisible = false
      onScriptPack(state.scriptPackData)
    })
}
function oddUploadChange(uploadFile) {
  state.oddDialogData = { ...state.oddDialogData, scriptFile: uploadFile.raw }
}
function ollUpload() {
  const formData = new FormData()
  formData.append('packageId', state.oddDialogData.packageId)
  formData.append('scriptCode', state.oddDialogData.scriptCode)
  formData.append('scriptName', state.oddDialogData.scriptName)
  formData.append('scriptFile', state.oddDialogData.scriptFile)
  $http
    .post('/api/script/upload', formData, {
      transformRequest: [], // 禁止数据转换
      headers: { 'Content-Type': 'multipart/form-data' },
    })
    .then((res) => {
      ElMessage.success('上传成功')
      state.oddDialogVisible = false
      onScriptPack(state.scriptPackData)
    })
}
function onDeletePack(){
  ElMessageBox.confirm('确定要删除这个脚本包吗？删除后将无法恢复，所有关联的脚本文件也将被删除。', '确认删除', {
    confirmButtonText: '确认删除',
    cancelButtonText: '取消',
    type: 'none',
  })
    .then(() => {
      $http.delete('/api/script-package/delete?packageId=' + state.scriptPackData.packageId).then((res) => {
        ElMessage.success('删除成功')
        getScriptPack()
      })
    })
}
</script>
<template>
  <div class="add-script-pack">
    <div class="add-script-pack-left">
      <span>脚本包管理</span>
      <span>管理升级所需的脚本包，每个包必须包含10个固定脚本</span>
    </div>
    <div class="add-script-pack-right" @click="addScriptPack">
      <AddIcon width="16" height="16" />
      <span class="add-script-pack-right-txt">新建空白脚本包</span>
    </div>
  </div>
  <div class="script-pack-content">
    <div class="w-full script-pack-list box-css w-1-3">
      <div class="script-pack-list-title">
        <div>脚本包列表</div>
        <el-input
          v-model="state.searchScriptPack"
          style="width: 140px"
          placeholder="搜索脚本包..."
          :prefix-icon="Search"
        />
      </div>
      <div
        class="script-pack-item"
        v-for="item in state.scriptPack"
        :key="item.packageId"
        :class="item.packageId == state.scriptPackActive"
        @click="onScriptPack(item)"
      >
        <div class="script-pack-item-top">
          <div class="flex-column">
            <span>{{ item.packageName }}</span>
            <span class="text-xs gray">创建于 {{ item.createTime }}</span>
          </div>
          <span
            class="script-pack-item-top-success"
            v-show="item.scriptCount == allPackageNameLength"
            >完整</span
          >
          <span
            class="script-pack-item-top-error"
            v-show="item.scriptCount < allPackageNameLength && item.scriptCount > 0"
          >
            不完整
          </span>
          <span class="script-pack-item-top-error" v-show="item.scriptCount == 0">未上传</span>
        </div>
        <div class="script-pack-item-bottom text-sm">
          <span class="gray">
            包含{{ item.scriptCount }}个脚本包
            <span v-show="item.scriptCount != allPackageNameLength"
              >（缺{{ allPackageNameLength - item.scriptCount }}个）</span
            >
          </span>
          <span class="highlight">查看详情</span>
        </div>
      </div>
      <div v-show="state.scriptPack.length == 0">
        <el-empty description="暂无脚本包" />
      </div>
      <div class="script-pack-tip text-sm">
        <span>提示：点击脚本包可查看详情，每个脚本包必须包含10个固定脚本才能使用</span>
      </div>
    </div>
    <div class="w-full script-pack-detail box-css w-2-3">
      <div class="script-pack-detail-title">
        <div class="flex-column">
          <span>{{state.scriptPackData.packageName}}</span>
          <span class="text-sm gray"
            >创建于 {{state.scriptPackData.createTime}} · 包含 {{ allPackageNameLength }} 个脚本</span
          >
        </div>
        <el-button type="danger" plain @click="onDeletePack">删除</el-button>
      </div>
      <div class="script-pack-detail-content">
        <div class="script-pack-detail-content-name">
          <div class="script-pack-detail-content-name-info">
            <el-icon class="highlight"><WarningFilled /></el-icon>
            <span class="mar-left">脚本包信息</span>
          </div>
          <div class="script-pack-detail-content-name-label text-sm gray">脚本包名称</div>
          <el-input
            class="script-pack-detail-content-name-value"
            v-model="state.scriptPackData.packageName"
            style="width: 100%"
            placeholder="请输入脚本包名称"
          />
          <div class="script-pack-detail-content-name-label text-sm gray">脚本包描述</div>
          <el-input
            class="script-pack-detail-content-name-value"
            v-model="state.scriptPackData.description"
            style="width: 100%"
            type="textarea"
            :rows="3"
            placeholder="请输入脚本包描述"
          />
          <el-button color="#165DFF" class="script-pack-detail-content-submit" @click="scriptPackSubmit">
            <SaveIcon width="14" height="14" />
            <span class="mar-left">保存信息</span>
          </el-button>
        </div>
        <div class="script-pack-detail-content-file">
          <div class="script-pack-detail-content-file-upload">
            <div class="flex-items-center">
              <ScriptFileIcon width="16" height="16" />
              <span class="mar-left">必需脚本文件</span>
            </div>
            <div class="script-pack-detail-content-file-upload-right flex-items-center" @click="state.moreDialogVisible = true">
              <UploadIcon width="14" height="14" />
              <span class="text-sm mar-left">批量上传脚本</span>
            </div>
          </div>
          <div class="script-pack-detail-content-file-tip flex-center">
            <el-icon class="highlight"><WarningFilled /></el-icon>
            <span class="text-sm mar-left"
              >每个脚本包必须包含以下10个固定脚本，文件名必须严格匹配</span
            >
          </div>
          <div class="script-pack-detail-content-file-table">
            <el-table :data="state.tableData" style="width: 100%" empty-text="暂无数据">
              <el-table-column prop="scriptName" label="脚本类型" width="180">
                <template #default="scope">
                  <span class="primary-tag" v-show="scope.row.scriptName">{{
                    scope.row.scriptName ? scope.row.scriptName : '—'
                  }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="scriptCode" label="文件名">
                <template #default="scope">
                  <div class="table-filename">
                    <span>{{ scope.row.scriptCode }}</span>
                    <span
                      class="mar-left"
                      :class="scope.row.uploadTime ? 'success-tag' : 'error-tag'"
                      >{{ scope.row.uploadTime ? '已上传' : '未上传' }}</span
                    >
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="uploadTime" label="上传时间" width="180">
                <template #default="scope">
                  <div class="table-filename">
                    <span>{{ scope.row.uploadTime ? scope.row.uploadTime : '—' }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120">
                <template #default="scope">
                  <div class="flex-center-between">
                    <LookIcon
                      class="cursor-pointer"
                      width="16"
                      height="16"
                      @click="openLookDialog(scope.row)"
                      v-show="scope.row.uploadTime"
                    />
                    <DownloadIcon
                      class="cursor-pointer"
                      width="16"
                      height="16"
                      v-show="scope.row.uploadTime"
                    />
                    <UploadIcon
                      class="cursor-pointer"
                      @click="openOddDialog(scope.row)"
                      width="16"
                      height="16"
                      v-show="!scope.row.uploadTime"
                    />
                    <ReplaceIcon
                      class="cursor-pointer"
                      width="16"
                      @click="openOddDialog(scope.row)"
                      height="16"
                      v-show="scope.row.uploadTime"
                    />
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <el-dialog
            v-model="state.moreDialogVisible"
            title="批量上传脚本"
            width="672px"
            align-center
          >
            <div class="odd-dialog">
              <div>请上传一个包含所需脚本的ZIP压缩包，支持的脚本文件包括：</div>
              <div class="file-list">
                <span class="file-item text-xs" v-for="item in state.allPackageName" :key="item">{{ item.id }}</span>
              </div>
              <el-upload
                action=""
                drag
                :auto-upload="false"
                show-file-list
                multiple
                :limit="allPackageNameLength"
                :on-change="moreUploadChange"
                :before-remove="removeMoreFile"
              >
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">点击或拖拽文件至此处上传（可多选）</div>
              </el-upload>
            </div>
            <template #footer>
              <div class="dialog-footer">
                <el-button @click="state.moreDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="moreUpload"> 确认上传 </el-button>
              </div>
            </template>
          </el-dialog>
          <el-dialog
            v-model="state.lookDialogVisible"
            :title="state.lookDialogTitle"
            width="80vh"
            align-center
          >
            <pre  class="look-dialog text-sm">{{ state.lookDialogData }}</pre>
            <template #footer>
              <div class="dialog-footer">
                <el-button @click="state.lookDialogVisible = false">关闭</el-button>
              </div>
            </template>
          </el-dialog>
          <el-dialog
            v-model="state.oddDialogVisible"
            :title="state.oddDialogTitle"
            width="500"
            align-center
          >
            <div class="odd-dialog">
              <div>请上传以下脚本文件，文件名必须严格匹配：</div>
              <div class="odd-dialog-file highlight">{{ state.oddDialogData.scriptCode }}</div>
              <el-input
                class="mar-bottom"
                v-model="state.oddDialogData.scriptName"
                style="width: 100%"
                placeholder="请输入脚本类型"
              />
              <el-upload
                action=""
                drag
                :auto-upload="false"
                show-file-list
                :on-change="oddUploadChange"
              >
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">点击或拖拽文件至此处上传</div>
              </el-upload>
            </div>
            <template #footer>
              <div class="dialog-footer">
                <el-button @click="state.oddDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="ollUpload"> 确认上传 </el-button>
              </div>
            </template>
          </el-dialog>
        </div>
      </div>
    </div>
  </div>
</template>
<style scoped lang="less">
.look-dialog{
  color: #f3f4f6;
  background-color: #1f2937;
  padding: 16px;
  border-radius: 8px;
  overflow-x: auto;
  height: 300px;
}
.odd-dialog {
  color: #333;
  .file-list{
    padding: 12px;
    background-color: #f2f3f5;
    border-radius: 8px;
    display: flex;
    flex-flow: wrap;
    gap: 8px;
    max-height: 128px;
    margin: 16px 0;
    .file-item{
      padding: 4px 8px;
      background-color: #ffffff;
      border-radius: 4px;
    }
  }
  .odd-dialog-file {
    padding: 12px;
    background-color: #f2f3f5;
    border-radius: 8px;
    margin: 16px 0 8px;
  }
  .mar-bottom {
    margin-bottom: 16px;
  }
}
.script-pack-content {
  display: flex;
  gap: 24px;
  width: 100%;
  flex-flow: wrap row;
  .mar-left {
    margin-left: 8px;
  }
  .script-pack-detail {
    .script-pack-detail-content {
      padding: 24px;
      .script-pack-detail-content-file {
        .script-pack-detail-content-file-tip {
          background-color: #f2f3f5;
          padding: 12px;
          border-radius: 8px;
          margin-bottom: 16px;
        }
        .script-pack-detail-content-file-upload {
          display: flex;
          align-items: center;
          margin-bottom: 12px;
          justify-content: space-between;
          .script-pack-detail-content-file-upload-right {
            color: #165dff;
            cursor: pointer;
          }
          .mar-left {
            margin-left: 4px;
          }
          .flex-items-center {
            display: flex;
            align-items: center;
          }
        }
      }
      .script-pack-detail-content-submit {
        float: right;
        margin: 12px 0 0;
      }
      .script-pack-detail-content-name-label {
        margin-bottom: 4px;
      }
      .script-pack-detail-content-name::after {
        content: '';
        display: block;
        clear: both;
      }
      .script-pack-detail-content-name {
        margin-bottom: 24px;
        .mar-left {
          margin-left: 6px;
        }
        .script-pack-detail-content-name-info {
          display: flex;
          align-items: center;
          margin-bottom: 12px;
        }
      }
    }
    .script-pack-detail-title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid #e5e7eb;
      padding: 16px;
    }
  }
  .script-pack-list {
    .script-pack-item:hover {
      background-color: rgba(249, 250, 251, 1);
    }
    .script-pack-item-active {
      background-color: rgba(249, 250, 251, 1);
    }
    .script-pack-item {
      padding: 16px;
      border-bottom: 1px solid #f3f4f6;
      cursor: pointer;
      .script-pack-item-top {
        display: flex;
        justify-content: space-between;

        .script-pack-item-top-error {
          padding: 2px 6px;
          color: #ff4d4f;
          font-size: 12px;
          line-height: 16px;
          height: fit-content;
          border-radius: 4px;
          background-color: rgb(255 77 79 / 0.1);
        }
        .script-pack-item-top-success {
          padding: 2px 6px;
          color: #52c41a;
          font-size: 12px;
          line-height: 16px;
          height: fit-content;
          border-radius: 4px;
          background-color: rgb(82 196 26 / 0.1);
        }
      }
      .flex-column {
        display: flex;
        flex-direction: column;
      }
      .script-pack-item-bottom {
        display: flex;
        justify-content: space-between;
        margin: 8px 0 0;
      }
    }
    .script-pack-tip {
      padding: 16px;
      border-radius: 0 0 8px 8px;
      color: #86909c;
      border-top: 1px solid #e5e7eb;
    }
    .script-pack-list-title {
      border-radius: 12px 12px 0 0;
      padding: 16px;
      background-color: #f9fafb;
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid #e5e7eb;
    }
  }
}
.box-css {
  border: 1px solid #e5e7eb;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  border-radius: 12px;
  background-color: #ffffff;
}
.add-script-pack {
  border: 1px solid #e5e7eb;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  border-radius: 12px;
  padding: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 0 0 24px;
  background-color: #ffffff;
  .add-script-pack-right:hover {
    background-color: rgba(23, 95, 255, 0.05);
  }
  .add-script-pack-right {
    border: 1px solid #165dff;
    display: flex;
    align-items: center;
    padding: 8px 12px;
    border-radius: 8px;
    cursor: pointer;
    .add-script-pack-right-txt {
      margin: 0 0 0 8px;
      color: #165dff;
    }
  }
  .add-script-pack-left {
    display: flex;
    flex-direction: column;
    span:nth-child(1) {
      font-size: 18px;
      line-height: 28px;
      font-weight: 800;
    }
    span:nth-child(2) {
      font-size: 14px;
      line-height: 20px;
      color: #86909c;
    }
  }
}
</style>
